package cn.yuhan.simplediary.system.service.impl;

import cn.yuhan.simplediary.base.UserRoleEnum;
import cn.yuhan.simplediary.system.service.UserService;
import cn.yuhan.simplediary.system.entity.User;
import cn.yuhan.simplediary.system.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public User findByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public void register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRole(UserRoleEnum.USER);
        user.setEnabled(true);
        userMapper.insert(user);
    }

    @Override
    public List<User> findAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public void disableUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setEnabled(false);
            userMapper.updateById(user);
        }
    }
}